import base64
import json
from pathlib import Path

import requests


# API端点
api_url = 'https://nlp.stonedt.com/api/text2voice'
SecretId = 'b2e12fc0-bf21-4b7f-99da-503f291eb6fe'
SecretKey = '278b1478cf8c21fef5ea0109bcde1ada'
headers = {
    "Content-Type": "application/json",
    "secret-id": SecretId,
    "secret-key": SecretKey
}



def getTextWav(text, i):
    try:
        request_data = {
            "text": text,
            "am": "fastspeech2_male",
            "voc": "pwgan_male",
            "lang": "mix",
            "spk_id": 0

        }
        # 发起POST请求
        response = requests.post(api_url, headers=headers, json=request_data)

        # 检查响应状态码
        if response.status_code == 200:
            # 将响应内容解码为字符串
            response_str = response.content.decode('utf-8')

            # 将字符串解析为JSON字典
            response_dict = json.loads(response_str)

            # 提取voice字段
            voice_data = response_dict.get('results', {}).get('voice', '')

            # 如果voice_data不为空，进行base64解码
            if voice_data:
                voice_bytes = base64.b64decode(voice_data)

                # 获取当前工作目录的路径，即项目的根目录
                project_root = Path.cwd()

                # 定义输出文件路径
                output_path = project_root / f'voice{i}.wav'

                # 将解码后的声音文件写入本地文件
                with output_path.open('wb') as voice_file:
                    voice_file.write(voice_bytes)

            # print(f"Voice file saved ")

        else:
            print(f"Error: {response.status_code}")

    except requests.exceptions.RequestException as e:
        # 打印异常信息
        print(f"An error occurred: {e}")



if __name__ == '__main__':
    getTextWav("你好")

